init('RoomService');
(function(){
	var Collections = require('Collections'),
	    ObjectUtils = require('ObjectUtils'),
	    GenericDataService = require('GenericDataService').constructor,
	    CommandChain       = require('CommandChain'),
	    session            = require('./Session').current;
	
	var List    = Collections.List,
	    toArray = Collections.toArray,
	    iterate = Collections.iterate;
	
	var merge   = ObjectUtils.merge,
	    copy    = ObjectUtils.copy,
	    inherit = ObjectUtils.inherit;
	
	namespace('org.jsmud');
	
	org.jsmud.RoomService = function(db){
		inherit.apply(this, [GenericDataService, arguments]);
	};
	org.jsmud.RoomService.prototype = {
		toEntity : function(record, onDone){
			var room = new org.jsmud.entity.Room(this, record);
			this.updateAssociations(room, onDone);
		},
		updateAssociations : function(room, onDone){
			var chain = CommandChain.create();
			chain
			  .add(this.refreshItems, [room, 'items', chain.next()], this)
			  .add(this.refreshExits, [room, 'exits', chain.next()], this)
			  .execute(function(){
				  if( onDone )
					  onDone(room);
			  });
		},
		refreshItems : function(room, type, onDone){
			var example = {'container.collectionName':'room', 'container._id':room.getId()}
			session.itemService.findByExample(example, function(results){
				results.toHTML = function(){
					var html = '';
					iterate(results, function(r){
						if( html ) html += ', ';
						html+=r.data.name;
					});
					return html;
				};
				room[type] = results;
				onDone(room);
			});
		},
		refreshExits : function(room, type, onDone){
			room.exits = [];
			iterate(room.data.exits, function(item){
				room.exits.push(item);
			});
			onDone(room);	
		}
	};
})();